package com.salim.leetcode.$6;

/**
 * Created with IntelliJ IDEA.
 * User: clevo
 * Date: 15-9-10
 * Time: 上午10:12
 * To change this template use File | Settings | File Templates.
 */
public class ZigZagConversion {
    public String convert(String s, int numRows) {
        //计算行数
        StringBuffer result = new StringBuffer();
        //奇数列数字个数=行数
        //偶数列数字个数=行数/2
        //步长(数字差)=奇数列个数+偶数列个数
        //列数基准=(长度/数字差)*2
        //列数余数=长度%数字差
        //列数= 基准 + (余数-奇-偶再得列数 反之）
        int singleColNumCount = numRows;
        int doubleColNumCount = numRows/2;
        int step = singleColNumCount + doubleColNumCount;
        int numColsA = (s.length()/step)*2;
        if(s.length()<=numRows){
            return s;
        }
        int numColsB = s.length()%step;
        int numColsC = 0;
        int numCols = 0;
        //基准为 14/4 A=6 B=4
        if(numColsB>singleColNumCount){
            numColsC++;
            numColsB=numColsB-singleColNumCount;
        }
        if(numColsB>doubleColNumCount){
            numColsC++;
            numColsB=numColsB-doubleColNumCount;
        }
        //总列数
        numCols = numColsA + numColsC;

        int[][] arrays = new int[numRows][numCols];
        int index = 0;
        for(int i=0;i<numCols;i++){
            if(index >= s.length()){
                break;
            }
            for(int j=0;j<numRows;j++){
                if(index >= s.length()){
                    break;
                }
                if(i%2==1){
                    //空白位不插
                    if(j%2==0){
                        arrays[j][i] = -1;
                        continue;
                    }
                }
                arrays[j][i] = index;
                index++;
            }
        }

        for(int i=0;i<numRows;i++){
            for(int j=0;j<numCols;j++){
                int indexTemp = arrays[i][j];
                if(indexTemp==0&&(i!=0||j!=0)){
                    continue;
                }
                if(indexTemp==-1){
                    continue;
                }
                result.append(s.charAt(indexTemp));
            }
        }
        return result.toString();
    }

    public static void main(String[] args){
        ZigZagConversion temp = new ZigZagConversion();
/*        String s ="PAYPALISHIRING";
        int row = 3;
        System.out.println(temp.convert(s,row));*/
        String a = "ABC";
        System.out.println(temp.convert(a,2));
    }
}
